<?php

class Controller_User extends Controller_Abstract
{
	function actionRegister()
	{
		if (isset($this->_context->cam)) {
			$cam = $this->_context->cam;
			$pub = $this->_context->pub;
			$pla = $this->_context->pla;
			$cus = $this->_context->cus;
			$cre = $this->_context->cre;
			$ind = $this->_context->ind;
			if (!empty($cam))
			{
				$params = array();
				$params['cam'] = $cam;
				$params['pub'] = $pub;
				$params['pla'] = $pla;
				$params['cre'] = $cre;
				$params['ind'] = $ind;
				if (empty($cus))
				{
					$params['cus'] = '';
				}
				else
				{
					$params['cus'] = $cus;
				}
				$_SESSION['campaign'] = $params;
			}
		}
		
		
		if (($user = $this->_app->currentUser()) === null) {
			$infos = array();
			if (isset($this->_context->gender)) {
				$infos['gender'] = ucwords($this->_context->get('gender'));
			}
			if (isset($this->_context->fname)) {
				$infos['fname'] = $this->_context->get('fname');
			}
			if (isset($this->_context->lname)) {
				$infos['lname'] = $this->_context->get('lname');
			}
			if (isset($this->_context->email)) {
				$infos['email'] = $this->_context->get('email');
			}
			if (isset($this->_context->birthday)) {
				$infos['birthday'] = $this->_context->get('birthday');
			}
			if (count($infos) > 0) {
				$_SESSION['accountinfo'] = $infos;
			}
		}
		
		if (isset($_SESSION['errors']))
		{
			$errors = $_SESSION['errors'];
			$this->_view['errors'] = $errors;
			unset($_SESSION['errors']);
		}
		if (isset($_SESSION['accountinfo'])) {
			$this->_view['accountinfo'] = $_SESSION['accountinfo'];
			if (isset($this->_view['accountinfo']['birthday']) && QValidator::validate_is_date($this->_view['accountinfo']['birthday'])) {
				$value = $this->_view['accountinfo']['birthday'];
				if (strpos($value, '-') !== false) {
		            $p = '-';
		        } elseif (strpos($value, '/') !== false) {
		            $p = '\/';
		        }
		        $birthday = explode($p, $this->_view['accountinfo']['birthday']);
				unset($this->_view['accountinfo']['birthday']);
				$this->_view['accountinfo']['birthYear'] = $birthday[0];
				$this->_view['accountinfo']['birthMonth'] = $birthday[1];
				$this->_view['accountinfo']['birthDay'] = $birthday[2];
			}
			unset($_SESSION['accountinfo']);
		}
		return $this->display($this->_site['template']);
	}
	
	function actionAccount()
	{
		if(!isset($this->_view['user'])){
			return $this->_redirect(url('user/signup'));
		}
		if(isset($_SESSION['infos'])){
			$this->_view['infos'] = $_SESSION['infos'];
			unset($_SESSION['infos']);
		}
		$rewardmodel = new Reward();
		$this->_view['user']['offers'] = $rewardmodel->getRewardsAll($this->_view['user']['id']);
		return $this->display($this->_site['template']);
	}
	
	function actionProfile()
	{
		if(isset($_SESSION['errors'])){
			$this->_view['errors'] = $_SESSION['errors'];
			unset($_SESSION['errors']);
		}
		if(isset($_SESSION['infos'])){
			$this->_view['infos'] = $_SESSION['infos'];
			unset($_SESSION['infos']);
		}
		if(isset($_SESSION['accountinfo'])){
			$this->_view['accountinfo'] = $_SESSION['accountinfo'];
			$user = $this->_app->currentUser();
			$usermodel = new User();
			$userInfo = $usermodel->getProfileInfo($user['id']);
			$this->_view['accountinfo']['optin_edu'] = $userInfo['optin_edu'];
			$this->_view['accountinfo']['optin_sj'] = $userInfo['optin_sj'];
			$this->_view['accountinfo']['optin_inpays'] = $userInfo['optin_inpays'];
			$this->_view['accountinfo']['optin_greateamerican'] = $userInfo['optin_greateamerican'];
		}elseif($user = $this->_app->currentUser()){
			$usermodel = new User();
			$userInfo = $usermodel->getProfileInfo($user['id']);
			$birthday = $userInfo['birthday'];
			$birth = explode('-', $birthday);
			if(count($birth) == 3){
				unset($userInfo['birthday']);
				$userInfo['birthDay'] = $birth[2];
				$userInfo['birthYear'] = $birth[0];
				$userInfo['birthMonth'] = $birth[1];
			}
			$phoneNums = explode('-', $userInfo['phone']);
			if(count($phoneNums) == 3){
				unset($userInfo['phone']);
				$userInfo['countryCode'] = $phoneNums[0];
				$userInfo['areaCode'] = $phoneNums[1];
				$userInfo['subscriberNumber'] = $phoneNums[2];
			}
			
			$this->_view['accountinfo'] = $userInfo;	
		}
		return $this->display($this->_site['template']);
	}

	function actionUpdate()
	{
		if(isset($_SESSION['errors'])){
			$errors = $_SESSION['errors'];
			$this->_view['errors'] = $errors;
			unset($_SESSION['errors']);
		}
		if($user = $this->_app->currentUser()){
			$this->_view['id'] = $user['id'];
			return $this->display($this->_site['template']);
		}else{
			$catption = '';
			$message = '';
			$url = '';
			return $this->_redirectMessage(
				$catption, 
				$message, 
				$url
			);	
		}
	}
	
	function actionLogin()
	{
		if(isset($_SESSION['errors']))
		{
			$errors = $_SESSION['errors'];
			$this->_view['errors'] = $errors;
			unset($_SESSION['errors']);
		}
		return $this->display($this->_site['template']);
	}
	function actionLogout()
	{
		$user = $this->_app->currentUser();	//	dump($user);
		$userId = $user['id'];
		$this->_app->cleanCurrentUser();
		session_destroy();
		setcookie(Q::ini('acl_cookie_key'), $userId, time()-60, '/', '' . $this->_site['domain'], 0, 1);
		return $this->_redirect(url('default/index'));
	}
	
	function actionForgetpassword()
	{
		if(isset($_SESSION['errors']))
		{
			$errors = $_SESSION['errors'];
			$this->_view['errors'] = $errors;
			unset($_SESSION['errors']);
		}
		return $this->display($this->_site['template']);
	}
	
	function actionSignin()
	{
		return $this->display($this->_site['template']);
	}
	
	function actionLogging()
	{
		if($this->_context->isPOST())
		{
			$infos = array();
			$errors = array();
			$usermodel = new User();
			$email = strtolower($this->_context->email);
			$password = $this->_context->password;
			if(isset($_POST['rememberMe']))
				$rememberMe = 0;
			else
				$rememberMe = false;
			if(empty($email)){
				$errors[] = Util::getMessage(1004);
			}
			else if(!QValidator::validate_is_email($email))
			{
				$errors[] = Util::getMessage(1014);
			}			
			if(empty($password))
			{
				$errors[] = Util::getMessage(1008);
			}
			$user = $usermodel->valid($email, $password, $this->_site['id']);
			if(!$user)
			{
				$errors[] = Util::getMessage(1019);
				$emodel = new Error();
				$emodel->addError($this->_site['name'], 'Login Failed: '.$email);
			}
			if(count($errors) == 0)
			{
				//refit old users's ip field
				if($user['ip'] == '' || $user['ip'] == 0){
					$usermodel->refitIp($user['id']);
				}
				
				$this->_app->changeCurrentUser(array('id'=>$user['id']), 'MEMBER');
				if($rememberMe === 0){
					$token = md5($email . time());
					$cookie = serialize(array($email, $token));
					setcookie(Q::ini('acl_cookie_key'), $cookie, time()+60*60*24*30, '/', '' . $this->_site['domain'], 0, 1);
					$usermodel->updateCookie($user['id'], $token);
				}
				$emodel = new Error();
				$emodel->addError($this->_site['name'], 'Login Successfully: '.$email);
				if(isset($_SESSION['played']))
					unset($_SESSION['played']);	
				return $this->_redirect(url('default/index'));
			}
			else
			{
				$_SESSION['errors'] = $errors;
				return $this->_redirect(url('user/login'));
			}
		}
	}
	
	function actionRegistering()
	{
		if($this->_context->isPOST())
		{
			$infos = array();
			$errors = array();
			$usermodel = new User();
			$email = strtolower($this->_context->email);
			$firstname = ucfirst($this->_context->firstname);
			$lastname = ucfirst($this->_context->lastname);
			$password = $this->_context->password;
			$repassword = $this->_context->repassword;
			$gender = $this->_context->gender;
			$birthMonth = $this->_context->birthMonth;
			$birthDay = $this->_context->birthDay;
			$birthYear = $this->_context->birthYear;
			$birthday = $birthYear . '/' . $birthMonth . '/' . $birthDay;
			$optin_edu = $this->_context->post('optin_edu', '0');
			$optin_sj = $this->_context->post('optin_sj', '0');
			$optin_inpays = $this->_context->post('optin_inpays', '0');
			$viewname = $this->_context->post('viewname', 'register');
			$domain = $this->getDomainByGameAndLocale($this->_site['game'], $this->_view['site']['locale']);
			
			if (empty($email))
			{
				$errors[] = Util::getMessage(1004);
			}
			else if (!QValidator::validate_is_email($email))
			{
				$errors[] = Util::getMessage(1014);
			}
			else if(Util::isUnAcceptedEmail($email))
			{
				$errors[] = Util::getMessage(1034);
			}
			else if ($usermodel->exist($email, $this->_site['id']))
			{
				$errors[] = Util::getMessage(1018);
			}
			if (empty($firstname))
			{
				$errors[] = Util::getMessage(1015);
			}
			if (empty($lastname))
			{
				$errors[] = Util::getMessage(1016);
			}
			if (empty($password))
			{
				$errors[] = Util::getMessage(1008);
			}
			if (empty($repassword))
			{
				$errors[] = Util::getMessage(1009);
			}
			if ($password != $repassword)
			{
				$errors[] = Util::getMessage(1010);
			}
			if (!isset($this->_context->terms))
			{
				$errors[] = Util::getMessage(1017);
			}
			if(!checkdate(intval($birthMonth), intval($birthDay), intval($birthYear))){
				$errors[] = Util::getMessage(1025);
			}
			$phone = '';
//			if ($optin_edu) {
//				$countryCode = $this->_context->countryCode;
//				$areaCode = $this->_context->areaCode;
//				$subscriberNumber = $this->_context->subscriberNumber;
//				$phone = $countryCode . '-' . $areaCode . '-' . $subscriberNumber;
//				if(!preg_match('/^\d{3}-\d{3}-\d{4}$/', $phone)){
//					$errors[] = Util::getMessage(1024);
//				}
//			}

			if (count($errors) == 0)
			{
				if ($this->_site['game'] == WHEEL)
				{
					$credit = 1;
				}
				else if ($this->_site['game'] == SLOT)
				{
					$credit = 5;
				}
				else if ($this->_site['game'] == POKER)
				{
					$credit = 1;
				}
				$credit = 0;
				$token = $usermodel->register($email, $password, $firstname, $lastname, $gender, $birthday, $phone, $this->_site['id'], $credit, '', '', $optin_edu, $optin_sj, $optin_inpays);
				$_SESSION['just_registered'] = true;
				$user = $usermodel->getUserByEmail($email, $this->_site['id']);
				if ($user == false)
				{
					header(Util::HTTPStatus(500));
					exit;
				}
				
				$optinModel = new Optin();
				if($optin_edu){
					$optinModel->addOptinUser($user['id']);
				}
				if($optin_sj){
					$optinModel->addShoppingJobsOptinUser($user['id']);
				}
				if($optin_inpays){
					$optinModel->addInPaysOptinUser($user['id']);
				}
				
				$who = $firstname . ' ' . substr($lastname, 0, 1);
				$what = 'Registered';
				$activitymodel = new Activity();
				$activitymodel->addActivity($who, $what, $this->_site['id']);
				$activeUrl = 'http://www.'. $this->_view['site']['domain'] . url('user/active', array('token'=>$token, 'name'=>md5($firstname)));
				$username = $firstname . ' ' . $lastname;
				//send an email to user
				Util::addNewEmail('register', $this->_site['template'], array('email'=>$email, 'firstname'=>$firstname
									, 'password' => $password, 'domain'=>$this->_site['domain'], 'name' => $this->_site['name'], 'activeUrl'=>$activeUrl, 'uid'=>$user['id'], 'priority'=>50));
				$this->_app->changeCurrentUser(array('id'=>$user['id']), 'MEMBER');	//	dump($this->_app->currentUser());
				
			
				$_SESSION['ga_title'] = 'Welcome to '. $this->_site['name'];
				if (!empty($_SESSION['campaign']))
				{
					$usermodel->recordCampaign($user['id'], $_SESSION['campaign']);
				}
				
				// fire pixel or not 
				$firePixel = true;
				$pixelmodel = new Pixel();
				if(isset($_SESSION['campaign'])){		
					$firePixel = $pixelmodel->firePixelOrNot($_SESSION['campaign'], 0);
					if($_SESSION['campaign']['cam'] == '10024'){
						$_SESSION['pixels'][] = array(
							'id' => 1,
							'site_id' => 1,
							'pos' => 'after_basic_reg',
							'type' => 0,
							'pixel' => "<script src='http://publishers.abaxinteractive.com/lead_third/10024/{$_SESSION['campaign']['pla']}'></script><noscript><img src='http://publishers.abaxinteractive.com/track_lead/10024/{$_SESSION['campaign']['pla']}'></noscript>"
						);
					}
				}// $firePixel = true;
				if($firePixel && (isset($_SESSION['campaign']) && $_SESSION['campaign']['cam'] != '17' && $_SESSION['campaign']['cam'] != '18')){
					$pixels = $pixelmodel->getPixels($this->_site['id'], 'after_basic_reg');
					foreach ($pixels as &$pixel)
					{
						$str = str_replace(array('[[CUSTOM_PARAMETER]]'), array(isset($_SESSION['campaign']['cus'])?$_SESSION['campaign']['cus']:''), $pixel['pixel']);
						$pixel['pixel'] = $str;
					}
					if (!empty($_SESSION['pixels']) && !empty($pixels))
					{
						$_SESSION['pixels'] = array_merge($_SESSION['pixels'], $pixels);
					}
					else if (!empty($pixels))
					{
						$_SESSION['pixels'] = $pixels;
					}
					$usermodel->setFired($user['id']);
				}
				else
				{
					$record = new Record($user['id']);
					$record->addSuppressedPixelRecording();
				}
				
				//TODO: recording basic register and free credits
//				$record = new Record($user['id']);
//				$record->addBasicRegRecording($credit, 'Fluent');
				
				//TODO: recording user's first playing before registering
				if (isset($_SESSION['PLAYED']))
				{
					$record = new Record($user['id']);
					$record->addPlayRecording(1, 0, 1);
					unset($_SESSION['PLAYED']);
				}
				
				$todaywon = $usermodel->getTodayWon($this->_site['id']);
				//addflow implementation
				$urlArgs = array('email'=>$email, 'gender'=>$gender, 'dobmonth'=>$birthMonth, 'dobday'=>$birthDay, 'dobyear'=>$birthYear
								,'firstname'=>$firstname, 'lastname'=>$lastname, 'won'=>$todaywon, 'header'=>$this->_site['jackpot']
				);
				
//				if ($optin_edu) {
//					$urlArgs['phonecode'] = $countryCode;
//					$urlArgs['phoneprefix'] = $areaCode;
//					$urlArgs['phonesuffix'] = $subscriberNumber;
//				}
				
				if(strtolower($this->_site['locale']) == 'uk'){
					if (false)
					{
						if($this->_site['game'] == WHEEL)
						{
							$jumpUrl = 'http://www.rewardsflow.com/?Flow=B353C2FE-89AF-4252-B890-D2C01CB609C1&isPrePop=true&';
						}
						else if ($this->_site['game'] == SLOT)
						{
							$jumpUrl = 'http://www.rewardsflow.com/?Flow=9CE4BAE4-F0C1-43B6-812C-09B056FD0E8B&isPrePop=true&';
						}
						else if ($this->_site['game'] == POKER)
						{
							$jumpUrl = 'http://www.rewardsflow.com/?Flow=64524D96-74FB-447D-9D5A-9B9A130F3867&isPrePop=true&';
						}
						$urlArgs['returnurl'] = $domain.url('user/registered').'?coreg=Fluent';
						$record = new Record($user['id']);
						$record->addBasicRegRecording($credit, 'Fluent');
					}
					else
					{
						if ($this->_site['game'] == WHEEL)
						{
							$header = 'http://image.cgb.s3.amazonaws.com/cashdazzle.co.uk/img/header-cashdazzle.png';
							$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=323314&t=17501&c=&a=111483&country=uk&';
						}
						else if ($this->_site['game'] == SLOT)
						{
							$header = 'http://image.cgb.s3.amazonaws.com/lalaloot.co.uk/img/header-lalaloot.png';
							$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=323315&t=17501&c=&a=111483&country=uk&';
						}
						else if ($this->_site['game'] == POKER)
						{
							$header = 'http://image.cgb.s3.amazonaws.com/mommymoolah.co.uk/img/herder-mommymoolah.png';
							$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=323316&t=17501&c=&a=111483&country=uk&';
						}
						$urlArgs = array('em'=>$email, 'fn'=>$firstname, 'ln'=>$lastname, 'bd_y'=>$birthYear, 'bd_m'=>$birthMonth, 'bd_d'=>$birthDay, 'ti'=>(strtolower($gender)=='m'?3:2), 'hi'=>$header);
						$urlArgs['redirect_url'] = $domain.url('user/registered').'?coreg=CoolSavings';
						$record = new Record($user['id']);
						$record->addBasicRegRecording($credit, 'CoolSavings');
					}
				}else{
					$settingModel = new Settings();
					$settingData = $settingModel->getConf();
					foreach($settingData as $v){
						$conf[$v['k']]=$v['v'];
					}
					$seeds = array();
					for($i = 0; $i < $conf['register_fluent_value']; $i++){
						$seeds[]='Fluent';
					}
					for($i = 0; $i < $conf['register_prospectiv_value']; $i++){
						$seeds[]='Prospectiv';
					}
					for($i = 0; $i < $conf['register_coolsavings_value']; $i++){
						$seeds[]='Coolsavings';
					}
					$ind = rand(0, (count($seeds)-1));
					
					if($this->_site['game'] == WHEEL)
					{
						if ($seeds[$ind] == 'Fluent')
//						if (true)
						{
							$jumpUrl = 'http://www.rewardsflow.com/?Flow=67EDC183-09A2-425B-BD01-05CE3C26AB02&isPrePop=true&';
							$urlArgs['returnurl'] = $domain.url('user/registered').'?coreg=Fluent';
							$record = new Record($user['id']);
							$record->addBasicRegRecording($credit, 'Fluent');
						}
						else if ($seeds[$ind] == 'Prospectiv')
						{
							$urlArgs = array('em'=>$email, 
											 'fn'=>$firstname, 
											 'ln'=>$lastname, 
											 'g'=>$gender, 
											 'dob'=>$birthMonth.$birthDay.$birthYear, 
											 'header'=>$this->_site['jackpot']);
							$jumpUrl = 'http://www.eversave.com/service/servlet/consumers.Redirect?rid=17567&';
							$urlArgs['r'] = $domain.url('user/registered').'?coreg=Prospectiv';
							$record = new Record($user['id']);
							$record->addBasicRegRecording($credit, 'Prospectiv');
						}
						else if ($seeds[$ind] == 'Coolsavings')
						{
							list($byear, $bmonth, $bday) = explode('-', $user['birthday']);
							$header = 'http://image.cgb.s3.amazonaws.com/cashdazzle.com/img/header-cashdazzle.png';
							$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=325199&c=&t=17501&a=111483&country=us&';
							$urlArgs = array('street'=>'_skip',
											 'state'=>'_skip',
											 'city'=>'_skip',
											 'zip'=>'_skip',
											 'em'=>$user['email'], 
											 'fn'=>$user['firstname'], 
											 'ln'=>$user['lastname'],
											 'phone'=>'_skip',
											 'bd_y'=>$byear, 
											 'bd_m'=>$bmonth, 
											 'bd_d'=>$bday, 
											 //'hi'=>$header
											 'ti'=>(strtolower($user['gender'])=='m'?3:2)
											 );
							$urlArgs['redirect_url'] = $domain.url('user/registered').'?coreg=CoolSavings';
							$record = new Record($user['id']);
							$record->addBasicRegRecording($credit, 'CoolSavings');
						}
					}
					else if ($this->_site['game'] == SLOT)
					{
						if ($seeds[$ind] == 'Fluent')
//						if (true)
						{
							$jumpUrl = 'http://www.rewardsflow.com/?Flow=3A4D9BD6-B17A-41A3-8345-310E048A7903&isPrePop=true&';
							$urlArgs['returnurl'] = $domain.url('user/registered').'?coreg=Fluent';
							$record = new Record($user['id']);
							$record->addBasicRegRecording($credit, 'Fluent');
						}
						else if ($seeds[$ind] == 'Prospectiv')
						{
							$urlArgs = array('em'=>$email, 'fn'=>$firstname, 'ln'=>$lastname, 'g'=>$gender, 'dob'=>$birthMonth.$birthDay.$birthYear, 'header'=>$this->_site['jackpot']);
							$jumpUrl = 'http://www.eversave.com/service/servlet/consumers.Redirect?rid=17573&';
							$urlArgs['r'] = $domain.url('user/registered').'?coreg=Prospectiv';
							$record = new Record($user['id']);
							$record->addBasicRegRecording($credit, 'Prospectiv');
						}
						else if ($seeds[$ind] == 'Coolsavings')
						{
							list($byear, $bmonth, $bday) = explode('-', $user['birthday']);
							$header = 'http://image.cgb.s3.amazonaws.com/lalaloot.com/img/header-lalaloot.png';
							$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=325206&c=&a=111483&t=17501&country=us&';
							$urlArgs = array('street'=>'_skip',
											 'state'=>'_skip',
											 'city'=>'_skip',
											 'zip'=>'_skip',
											 'em'=>$user['email'], 
											 'fn'=>$user['firstname'], 
											 'ln'=>$user['lastname'],
											 'phone'=>'_skip',
											 'bd_y'=>$byear, 
											 'bd_m'=>$bmonth, 
											 'bd_d'=>$bday, 
											 //'hi'=>$header
											 'ti'=>(strtolower($user['gender'])=='m'?3:2)
											 );
							$urlArgs['redirect_url'] = $domain.url('user/registered').'?coreg=CoolSavings';
							$record = new Record($user['id']);
							$record->addBasicRegRecording($credit, 'CoolSavings');
						}
					}
					else if ($this->_site['game'] == POKER)
					{
						if ($seeds[$ind] == 'Fluent')
//						if (true)
						{
							$jumpUrl = 'http://www.rewardsflow.com/?Flow=1F9FAEC5-34B9-484C-B14C-6E99837503A9&isPrePop=true&';
							$urlArgs['returnurl'] = $domain.url('user/registered').'?coreg=Fluent';
							$record = new Record($user['id']);
							$record->addBasicRegRecording($credit, 'Fluent');
						}
						else if ($seeds[$ind] == 'Prospectiv')
						{
							$urlArgs = array('em'=>$email, 'fn'=>$firstname, 'ln'=>$lastname, 'g'=>$gender, 'dob'=>$birthMonth.$birthDay.$birthYear, 'header'=>$this->_site['jackpot']);
							$jumpUrl = 'http://www.eversave.com/service/servlet/consumers.Redirect?rid=17570&';
							$urlArgs['r'] = $domain.url('user/registered').'?coreg=Prospectiv';
							$record = new Record($user['id']);
							$record->addBasicRegRecording($credit, 'Prospectiv');
						}
						else if ($seeds[$ind] == 'Coolsavings')
						{
							list($byear, $bmonth, $bday) = explode('-', $user['birthday']);
							$header = 'http://image.cgb.s3.amazonaws.com/mommymoolah.com/img/header-mommymoolah.png';
							$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=323331&c=&a=111483&t=17501&country=us&';
							$urlArgs = array('street'=>'_skip',
											 'state'=>'_skip',
											 'city'=>'_skip',
											 'zip'=>'_skip',
											 'em'=>$user['email'], 
											 'fn'=>$user['firstname'], 
											 'ln'=>$user['lastname'],
											 'phone'=>'_skip',
											 'bd_y'=>$byear, 
											 'bd_m'=>$bmonth, 
											 'bd_d'=>$bday, 
											 //'hi'=>$header
											 'ti'=>(strtolower($user['gender'])=='m'?3:2)
											 );
							$urlArgs['redirect_url'] = $domain.url('user/registered').'?coreg=CoolSavings';
							$record = new Record($user['id']);
							$record->addBasicRegRecording($credit, 'CoolSavings');
						}
					}
				}
				
				//add credit to referee
/*				if(isset($_SESSION['campaign']) && ($_SESSION['campaign']['pub'] == 'wb' || $_SESSION['campaign']['pub'] == 'fb' || $_SESSION['campaign']['pub'] == 'tw' ||$_SESSION['campaign']['pub'] == 'ld')){
					if ($this->_site['game'] == WHEEL){
						$referenceCredit = 1;
					}else if ($this->_site['game'] == SLOT){
						$referenceCredit = 5;
					}else if ($this->_site['game'] == POKER){
						$referenceCredit = 1;
					}
					$usermodel->rewardReference($_SESSION['campaign']['pla'], $referenceCredit, 'Referred '.$email);
					
					unset($_SESSION['campaign']);
				}else
*/				if(isset($_SESSION['campaign'])){
					if (isset($_SESSION['campaign']['pub']) && $_SESSION['campaign']['pub'] == 'em')
					{
						$emailModel = new Email();
						$emailModel->setConfirmed($_SESSION['campaign']['ind']);
					}
					unset($_SESSION['campaign']);
				}
				$_SESSION['iframe_breaker'] = true;
				$_SESSION['redirect_url'] = $jumpUrl . http_build_query($urlArgs);
				
				$parSub_Mdel = new PartnerSubscriber();
				$parSub_Mdel->addNewRegUser($user['id']);
				$parSub_Mdel->addToSubUser_AIB($user['id']);
				$parSub_Mdel->addToSubUser_RG($user['id']);
				$parSub_Mdel->addToSubUser_PLive($user['id']);
				
				return $this->_redirect(url('offer/coreg'));
				
//				return $this->_redirect(url('user/registered'));
			}
			else
			{
				$accountinfo = array();
				$accountinfo['fname'] = $firstname;
				$accountinfo['lname'] = $lastname;
				$accountinfo['email'] = $email;
				$accountinfo['gender'] = $gender;
				$accountinfo['birthday'] = $birthYear . '-' . $birthMonth . '-' . $birthDay;
				if ($optin_edu) {
					$accountinfo['optin_edu'] = $optin_edu;
				}
				if ($optin_sj) {
					$accountinfo['optin_sj'] = $optin_sj;
				}
				if ($optin_inpays) {
					$accountinfo['optin_inpays'] = $optin_inpays;
				}

				$_SESSION['accountinfo'] = $accountinfo;
				$_SESSION['errors'] = $errors;
				
				$redirectController = 'user';
				if($viewname == "landingpage"){
					$redirectController = 'default';
				}
				return $this->_redirect(url($redirectController . '/' . $viewname));
			}
		}
	}
	
	function actionRegistered(){
		if (!empty($_SESSION['iframe_breaker']))
		{
			unset($_SESSION['iframe_breaker']);
			return $this->display($this->_site['template'], 'common/iframebreaker');
		}
		if ($this->_site['game'] == WHEEL)
		{
			$credit = 1;
		}
		else if ($this->_site['game'] == SLOT)
		{
			$credit = 5;
		}
		else if ($this->_site['game'] == POKER)
		{
			$credit = 1;
		}
		if (!empty($_SESSION['just_registered']))
		{
			$umodel = new User();
			$umodel->offerUserCredits($credit, $this->_view['user']['id']);
			unset($_SESSION['just_registered']);
			$u = $umodel->getUserById($this->_view['user']['id']);
			$this->_view['user'] = $u;
		}
		//TODO: add basic_reg_coreg event
		
		$coreg = $this->_context->coreg;
		$record = new Record($this->_view['user']['id']);
		$record->addCoregRecording('basic_reg_coreg', $coreg);
		
		$this->_view['showmonkey'] = true;
		return $this->display($this->_site['template'], 'default/index');
	}
	
	function actionForgetting()
	{
		if($this->_context->isPOST())
		{
			$errors = array();
			$email = strtolower($this->_context->email);
			$usermodel = new User();
			if(empty($email))
			{
				$errors[] = Util::getMessage(1004);
			}
			else if(!QValidator::validate_is_email($email))
			{
				$errors[] = Util::getMessage(1014);
			}
			else if (!$user = $usermodel->exist($email, $this->_site['id']))
			{
				$errors[] = Util::getMessage(1020);
			}
			if(count($errors) == 0)
			{
				if($password = $usermodel->forgetPassword($email, $this->_site['id'])){
					if(Util::addNewEmail('reset', $this->_site['template'], 
							array('email'=>$email, 'username' => $user['firstname'] . ' ' . $user['lastname']
								, 'domain'=>$this->_view['site']['domain'], 'password' => $password, 'uid'=>$user['id'], 'priority'=>100))){
						$infos = array();
						$infos[] = Util::getMessage(1028);
						$_SESSION['infos'] = $infos;
						$emodel = new Error();
						$emodel->addError($this->_site['name'], 'Ask for Password: '.$email);
					}
				} else {
					$errors[] = Util::getMessage(1029);
					$_SESSION['errors'] = $errors;
				}
				return $this->_redirect(url('user/forgetted'));
			}
			else
			{
				$_SESSION['errors'] = $errors;
				return $this->_redirect(url('user/forgetpassword'));
			}	
		}
	}
	
	
	
	function actionForgetted()
	{
		if(isset($_SESSION['infos'])){
			$this->_view['infos'] = $_SESSION['infos'];
			unset($_SESSION['info']);
		}
		if(isset($_SESSION['errors'])){
			$this->_view['errors'] = $_SESSION['errors'];
			unset($_SESSION['errors']);
		}	
		return $this->display($this->_site['template']);
	}
	
	function actionUpdating()
	{
		if($this->_context->isPOST()){
			$errors= array();
			$password = $this->_context->password;
			$repassword = $this->_context->repassword;
			if(empty($password)){
				$errors[] = Util::getMessage(1008);
			}elseif (empty($repassword)){
				$errors[] = Util::getMessage(1009);
			}elseif ($password != $repassword){
				$errors[] = Util::getMessage(1010);
			}elseif (strlen($password) < 6){
				$errors[] = Util::getMessage(1026);
			}elseif (!ctype_alnum($password)){
				$errors[] = Util::getMessage(1027);
			}
			if(count($errors) == 0){
				if($user = $this->_app->currentUser()){
					$user_model = new User();
					$flag = $user_model->updatePassword($user['id'], $password);
					if($flag){
						$infos = array();
						$infos[] = Util::getMessage(1011);
						$_SESSION['infos'] = $infos;
						return $this->_redirect(url('user/account'));
					} else {
						$errros[] = Util::getMessage(1000);
						$_SESSION['errors'] = $errors;
						return $this->_redirect(url('user/update'));
					}
				}
			}else{
				$_SESSION['errors'] = $errors;
				return $this->_redirect(url('user/update'));
			}		
		}
	}
	function actionProfiling()
	{
		if($this->_context->isPOST()){
			$errors = array();
			$email = strtolower($this->_context->email);
			$firstname = ucfirst($this->_context->firstname);
			$lastname = ucfirst($this->_context->lastname);
			$address1 = $this->_context->address1;
			$address2 = $this->_context->address2;
			$gender = $this->_context->gender;
			$city = $this->_context->city;
			$state = $this->_context->state;
			$zipcode = $this->_context->zipcode;
			if(strtolower($this->_site['locale']) == 'uk'){
				$phone = $this->_context->phone;
				$countryCode = '0044';
				$areaCode = '';
				$subscriberNumber = '';
			}else{
				$countryCode = $this->_context->countryCode;
				$areaCode = $this->_context->areaCode;
				$subscriberNumber = $this->_context->subscriberNumber;
				$phone = $countryCode . '-' . $areaCode . '-' . $subscriberNumber;
			}
			$birthMonth = $this->_context->birthMonth;
			$birthDay = $this->_context->birthDay;
			$birthYear = $this->_context->birthYear;
			$birthday = $birthYear . '/' . $birthMonth . '/' . $birthDay;
			$optin_edu = $this->_context->post('optin_edu', 0);
			$optin_sj = $this->_context->post('optin_sj', 0);
			$optin_inpays = $this->_context->post('optin_inpays', 0);
			$optin_greateamerican = $this->_context->post('optin_greateamerican', 0);
			
			$domain = $this->getDomainByGameAndLocale($this->_site['game'], $this->_view['site']['locale']);
			
			if(empty($email)){
				$errors[] = Util::getMessage(1004);
			}
			else if(!QValidator::validate_is_email($email))
			{
				$errors[] = Util::getMessage(1014);
			}
			if(empty($firstname)){
				$errors[] = Util::getMessage(1015);
			}
			if(empty($lastname)){
				$errors[] = Util::getMessage(1016);
			}
			if(empty($address1)){
				$errors[] = Util::getMessage(1021);
			}
			if(empty($zipcode)){
				$errors[] = Util::getMessage(1022);
			}else{
				if(strtolower($this->_site['locale']) == 'uk'){
					if(Util::parseUkPostcode($zipcode) == NULL){
						$errors[] = Util::getMessage(1031);
					}
				}else{
					if(!preg_match('/^\d{5}$/', $zipcode)){
						$errors[] = Util::getMessage(1023);
					}
				}
			}
			if(empty($phone)){
				$errors[] = Util::getMessage(1032);
			}else{
				if(strtolower($this->_site['locale']) == 'uk'){
					if(!Util::checkUKTelephone($phone, $errorCode, $errorStr)){
						$errors[] = $errorStr;
					}
				}else{
					if(!preg_match('/^\d{3}-\d{3}-\d{4}$/', $phone)){
						$errors[] = Util::getMessage(1024);
					}
				}
			}
			if(!checkdate(intval($birthMonth), intval($birthDay), intval($birthYear))){
				$errors[] = Util::getMessage(1025);
			}
			
			if(count($errors) == 0){
				$user = $this->_app->currentUser();
				$uid = $user['id'];
				$usermodel = new User();
				$todaywon = $usermodel->getTodayWon($this->_site['id']);
				$u = $usermodel->getUserById($uid);
					
				$optinModel = new Optin();
				if($optin_edu){
					$optinModel->addOptinUser($u['id']);
				}
				if($optin_sj){
					$optinModel->addShoppingJobsOptinUser($u['id']);
				}
				if($optin_inpays){
					$optinModel->addInPaysOptinUser($u['id']);
				}
				if($optin_greateamerican){
					$optinModel->addGreateAmericanUser($u['id']);
				}
				if($u['optin_edu'] == '1'){
					$optin_edu = '1';
				}
				if($u['optin_sj'] == '1'){
					$optin_sj = '1';
				}
				if($u['optin_inpays'] == '1'){
					$optin_inpays = '1';
				}
				if($u['optin_greateamerican'] == '1'){
					$optin_greateamerican = '1';
				}
				$usermodel->updateProfile($uid, $email, $firstname, $lastname, $address1, $address2, $city, $state, $zipcode, $phone, $gender, $birthday, $optin_edu, $optin_sj, $optin_inpays, $optin_greateamerican);
				if(isset($_SESSION['accountinfo']))
					unset($_SESSION['accountinfo']);
				$infos = array();
				$infos[] = Util::getMessage(1007);
				$_SESSION['infos'] = $infos;
				
				$settingModel = new Settings();
				$settingData = $settingModel->getConf();
				foreach($settingData as $v){
					$conf[$v['k']]=$v['v'];
				}
				$seeds = array();
				for($i = 0; $i < $conf['profile_fluent_value']; $i++){
					$seeds[]='Fluent';
				}
				for($i = 0; $i < $conf['profile_prospectiv_value']; $i++){
					$seeds[]='Prospectiv';
				}
				for($i = 0; $i < $conf['profile_coolsavings_value']; $i++){
					$seeds[]='Coolsavings';
				}
				$ind = rand(0, (count($seeds)-1));
				$seed = $seeds[$ind];
				if(empty($u['address1']))
				{
					$_SESSION['accountinfo']['email'] = $email;
					$_SESSION['accountinfo']['firstname'] = $firstname;
					$_SESSION['accountinfo']['lastname'] = $lastname;
					$_SESSION['accountinfo']['address1'] = $address1;
					$_SESSION['accountinfo']['address2'] = $address2;
					$_SESSION['accountinfo']['gender'] = $gender;
					$_SESSION['accountinfo']['city'] = $city;
					$_SESSION['accountinfo']['zipcode'] = $zipcode;
					if(strtolower($this->_site['locale']) == 'uk'){
						$phone = $this->_context->phone;
						$_SESSION['accountinfo']['phone'] = $phone;
					}else{
						$_SESSION['accountinfo']['countryCode'] = $countryCode;
						$_SESSION['accountinfo']['areaCode'] = $areaCode;
						$_SESSION['accountinfo']['subscriberNumber'] = $subscriberNumber;
					}
					$_SESSION['accountinfo']['birthDay'] = $birthDay;
					$_SESSION['accountinfo']['birthMonth'] = $birthMonth;
					$_SESSION['accountinfo']['birthYear'] = $birthYear;
					$_SESSION['ga_title_full_reg'] = 'Profile Updated';
					
					
					$firePixel = true;
					$pixelmodel = new Pixel();
					if(!empty($u['cam'])){
						$firePixel = $pixelmodel->firePixelOrNot(array('cam'=>$u['cam'], 'pub'=>$u['pub'], 'pla'=>$u['pla']), 1);
					}
					if ($firePixel && ($u['cam'] != '17' && $u['cam'] != '18')){
						$pixels = $pixelmodel->getPixels($this->_site['id'], 'after_full_reg');
						foreach ($pixels as &$pixel)
						{
							$str = str_replace(array('[[CUSTOM_PARAMETER]]'), array(isset($_SESSION['campaign']['cus'])?$_SESSION['campaign']['cus']:''), $pixel['pixel']);
							$pixel['pixel'] = $str;
						}
						if (!empty($_SESSION['pixel']) && !empty($pixels))
						{
							$_SESSION['pixels'] = array_merge($_SESSION['pixels'], $pixels);
						}
						else if (!empty($pixels))
						{
							$_SESSION['pixels'] = $pixels;
						}
						$usermodel->setFired($uid);
					}
					else {
						$record = new Record($uid);
						$record->addSuppressedPixelRecording();
					}
					if(strtolower($this->_site['locale']) == 'uk'){
						//if (strtoupper($gender) == 'M')
						//if ($seed == 'Fluent')
						if(true)
						{
							$credit = 0;
							if($this->_site['game'] == WHEEL)
							{
								$header = 'http://image.cgb.s3.amazonaws.com/cashdazzle.co.uk/img/header-cashdazzle.png';
								$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=323314&t=17501&c=&a=111483&country=uk&';
								$credit = 2;
							}
							else if ($this->_site['game'] == SLOT)
							{
								$header = 'http://image.cgb.s3.amazonaws.com/lalaloot.co.uk/img/header-lalaloot.png';
								$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=323315&t=17501&c=&a=111483&country=uk&';
								$credit = 10;
							}
							else if ($this->_site['game'] == POKER)
							{
								$header = 'http://image.cgb.s3.amazonaws.com/mommymoolah.co.uk/img/herder-mommymoolah.png';
								$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=323316&t=17501&c=&a=111483&country=uk&';
								$credit = 2;
							}
							$urlArgs = array('em'=>$email, 'fn'=>$firstname, 'ln'=>$lastname, 'bd_y'=>$birthYear, 'bd_m'=>$birthMonth, 'bd_d'=>$birthDay, 'ti'=>(strtolower($gender)=='m'?3:2), 
								'a1' => $address1, 'ci'=>$city, 'zi'=>$zipcode, 'phone'=>$phone, 'hi'=>$header);
							//$usermodel->offerUserCredits($credit, $uid);
							$urlArgs['redirect_url'] = $domain . url('user/completed').'?event=full_reg_coreg&coreg=CoolSavings';
							$usermodel->offerUserCredits($credit, $uid);
							$record = new Record($uid);
							$record->addFreeCreditsRecording($credit);
							$record = new Record($uid);
							$record->addFullRegRecording($credit, 'CoolSavings');
							$_SESSION['redirect_url'] = $jumpUrl . http_build_query($urlArgs);
							return $this->_redirect(url('offer/coreg'));
						}else{
							$urlArgs = array('email'=>$email, 'gender'=>$gender, 'dobmonth'=>$birthMonth, 'dobday'=>$birthDay, 'dobyear'=>$birthYear
								,'firstname'=>$firstname, 'lastname'=>$lastname, 'address1'=>$address1, 'address2'=>$address2,'city'=>$city
								,'state'=>$state,'zip'=>$zipcode,'phonecode'=>$countryCode,'phoneprefix'=>$areaCode,'phonesuffix'=>$subscriberNumber, 'won'=>$todaywon, 'header'=>$this->_site['jackpot']
							);
							if($this->_site['game'] == WHEEL)
							{
								$jumpUrl = 'http://www.rewardsflow.com/?Flow=B353C2FE-89AF-4252-B890-D2C01CB609C1&isPrePop=true&';
								$credit = 2;
							}
							else if ($this->_site['game'] == SLOT)
							{
								$jumpUrl = 'http://www.rewardsflow.com/?Flow=9CE4BAE4-F0C1-43B6-812C-09B056FD0E8B&isPrePop=true&';
								$credit = 10;
							}
							else if ($this->_site['game'] == POKER)
							{
								$jumpUrl = 'http://www.rewardsflow.com/?Flow=64524D96-74FB-447D-9D5A-9B9A130F3867&isPrePop=true&';
								$credit = 2;
							}
							$urlArgs['returnurl'] = $domain . url('user/completed').'?event=full_reg_coreg&coreg=Fluent';
							$record = new Record($uid);
							$record->addFullRegRecording($credit, 'Fluent');
							$record = new Record($uid);
							$record->addFreeCreditsRecording($credit);
							
							$_SESSION['redirect_url'] = $jumpUrl . http_build_query($urlArgs);
							$_SESSION['iframe_breaker'] = true;
							return $this->_redirect(url('offer/coreg'));
						}
					}else{
						//if (strtoupper($gender) == 'M')
						if ($seed == 'Fluent')
//						if(false)
						{
							$urlArgs = array('email'=>$email, 'gender'=>$gender, 'dobmonth'=>$birthMonth, 'dobday'=>$birthDay, 'dobyear'=>$birthYear
									,'firstname'=>$firstname, 'lastname'=>$lastname, 'address1'=>$address1, 'address2'=>$address2,'city'=>$city
									,'state'=>$state,'zip'=>$zipcode,'phonecode'=>$countryCode,'phoneprefix'=>$areaCode,'phonesuffix'=>$subscriberNumber, 'won'=>$todaywon, 'header'=>$this->_site['jackpot']
							);
							$credit = 0;
							if($this->_site['game'] == WHEEL)
							{
//								$usermodel->offerUserCredits(2, $uid);
								$jumpUrl = 'http://www.rewardsflow.com/?Flow=F78B19DD-529A-4452-B595-334BEA911346&isPrePop=true&';
								$urlArgs['returnurl'] = $domain . url('user/completed').'?event=full_reg_coreg&coreg=Fluent';
								$credit = 2;
							}
							else if ($this->_site['game'] == SLOT)
							{
//								$usermodel->offerUserCredits(10, $uid);
								$jumpUrl = 'http://www.rewardsflow.com/?Flow=8314C0AD-F6C1-4372-883A-D4F807E6ADB7&isPrePop=true&';
								$urlArgs['returnurl'] = $domain . url('user/completed').'?event=full_reg_coreg&coreg=Fluent';
								$credit = 10;
							}
							else if ($this->_site['game'] == POKER)
							{
//								$usermodel->offerUserCredits(2, $uid);
								$jumpUrl = 'http://www.rewardsflow.com/?Flow=913EB1B0-7141-4F2C-95A7-09C5E8882219&isPrePop=true&';
								$urlArgs['returnurl'] = $domain . url('user/completed').'?event=full_reg_coreg&coreg=Fluent';
								$credit = 2;
							}
							$usermodel->offerUserCredits($credit, $uid);
							$record = new Record($uid);
							$record->addFreeCreditsRecording($credit);
							$record = new Record($uid);
							$record->addFullRegRecording($credit, 'Fluent');
						
							$_SESSION['redirect_url'] = $jumpUrl . http_build_query($urlArgs);
							return $this->_redirect(url('offer/coreg'));
						}else if ($seed == 'Prospectiv'){
							$urlArgs = array('em'=>$email, 'fn'=>$firstname, 'ln'=>$lastname, 'a1'=>$address1, 'a2'=>$address2, 'ci'=>$city, 'st'=>$state, 'zi'=>$zipcode, 'g'=>$gender, 'dob'=>$birthMonth.$birthDay.$birthYear, 'ph'=>$countryCode.$areaCode.$subscriberNumber, 'header'=>$this->_site['jackpot']);
							if($this->_site['game'] == WHEEL)
							{
								$jumpUrl = 'http://www.eversave.com/service/servlet/consumers.Redirect?rid=17568&';
								$urlArgs['r'] = $domain.url('user/completed').'?event=full_reg_coreg&coreg=Prospectiv';
								$credit = 2;
							}
							else if ($this->_site['game'] == SLOT)
							{
								$jumpUrl = 'http://www.eversave.com/service/servlet/consumers.Redirect?rid=17574&';
								$urlArgs['r'] = $domain.url('user/completed').'?event=full_reg_coreg&coreg=Prospectiv';
								$credit = 10;
							}
							else if ($this->_site['game'] == POKER)
							{
								$jumpUrl = 'http://www.eversave.com/service/servlet/consumers.Redirect?rid=17571&';
								$urlArgs['r'] = $domain.url('user/completed').'?event=full_reg_coreg&coreg=Prospectiv';
								$credit = 2;
							}
							$record = new Record($uid);
							$record->addFullRegRecording($credit, 'Prospectiv');
							$usermodel->offerUserCredits($credit, $uid);
							$record = new Record($uid);
							$record->addFreeCreditsRecording($credit);
							
							$_SESSION['redirect_url'] = $jumpUrl . http_build_query($urlArgs);
							$_SESSION['iframe_breaker'] = true;
							return $this->_redirect(url('offer/coreg'));
						}
						else if($seed == "Coolsavings"){
							if ($this->_site['game'] == WHEEL)
							{
								$header = 'http://image.cgb.s3.amazonaws.com/cashdazzle.com/img/header-cashdazzle.png';
								$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=325202&c=&a=111483&t=17501&country=us&';
								$credit = 2;
							}
							else if ($this->_site['game'] == SLOT)
							{
								$header = 'http://image.cgb.s3.amazonaws.com/lalaloot.com/img/header-lalaloot.png';
								$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=325208&c=&a=111483&t=17501&country=us&';
								$credit = 10;
							}
							else if ($this->_site['game'] == POKER)
							{
								$header = 'http://image.cgb.s3.amazonaws.com/mommymoolah.com/img/herder-mommymoolah.png';
								$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=325211&c=&a=111483&t=17501&country=us&';
								$credit = 2;
							}
							$urlArgs = array('a1'=>$address1,
											 'st'=>$state,
											 'ci'=>$city,
											 'zi'=>$zipcode,
											 'em'=>$email, 
											 'fn'=>$firstname, 
											 'ln'=>$lastname,
											 'phone'=>$phone,
											 'bd_y'=>$birthYear,
											 'bd_m'=>$birthMonth, 
											 'bd_d'=>$birthDay, 
											 //'hi'=>$header
											 'ti'=>(strtolower($gender)=='m'?3:2)
											 );
							$urlArgs['redirect_url'] = $domain.url('user/completed').'?event=full_reg_coreg&coreg=CoolSavings';
							$record = new Record($uid);
							$record->addFullRegRecording($credit, 'CoolSavings');
							$usermodel->offerUserCredits($credit, $uid);
							$record = new Record($uid);
							$record->addFreeCreditsRecording($credit);
							
							$_SESSION['redirect_url'] = $jumpUrl . http_build_query($urlArgs);
							$_SESSION['iframe_breaker'] = true;
							return $this->_redirect(url('offer/coreg'));				
						}
					}
				}
				if(isset($_SESSION['accountinfo'])){
					unset($_SESSION['accountinfo']);
				}
				if(strtolower($this->_site['locale']) == 'uk')
				{
					//if (strtoupper($gender) == 'M')
					if ($seed == 'Fluent')
//					if (true)
					{
						if($this->_site['game'] == WHEEL)
						{
							$header = 'http://image.cgb.s3.amazonaws.com/cashdazzle.co.uk/img/header-cashdazzle.png';
							$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=323314&t=17501&c=&a=111483&country=uk&';
						}
						else if ($this->_site['game'] == SLOT)
						{
							$header = 'http://image.cgb.s3.amazonaws.com/lalaloot.co.uk/img/header-lalaloot.png';
							$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=323315&t=17501&c=&a=111483&country=uk&';
						}
						else if ($this->_site['game'] == POKER)
						{
							$header = 'http://image.cgb.s3.amazonaws.com/mommymoolah.co.uk/img/herder-mommymoolah.png';
							$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=323316&t=17501&c=&a=111483&country=uk&';
						}
						$urlArgs = array('em'=>$email, 'fn'=>$firstname, 'ln'=>$lastname, 'bd_y'=>$birthYear, 'bd_m'=>$birthMonth, 'bd_d'=>$birthDay, 'ti'=>(strtolower($gender)=='m'?3:2),
							'a1' => $address1, 'ci'=>$city, 'zi'=>$zipcode, 'phone'=>$phone, 'hi'=>$header);
						$urlArgs['redirect_url'] = $domain . url('user/completed').'?event=full_reg_coreg&coreg=CoolSavings';
						$_SESSION['redirect_url'] = $jumpUrl . http_build_query($urlArgs);
						$record = new Record($uid);
						$record->addCoregRecording('profiling_coreg_start', 'CoolSavings');
						return $this->_redirect(url('offer/coreg'));
					}else if ($seed == 'Prospectiv'){
						$urlArgs = array('email'=>$email, 'gender'=>$gender, 'dobmonth'=>$birthMonth, 'dobday'=>$birthDay, 'dobyear'=>$birthYear
							,'firstname'=>$firstname, 'lastname'=>$lastname, 'address1'=>$address1, 'address2'=>$address2,'city'=>$city
							,'state'=>$state,'zip'=>$zipcode,'phonecode'=>$countryCode,'phoneprefix'=>$areaCode,'phonesuffix'=>$subscriberNumber, 'won'=>$todaywon, 'header'=>$this->_site['jackpot']
						);
						if($this->_site['game'] == WHEEL)
						{
							$jumpUrl = 'http://www.rewardsflow.com/?Flow=B353C2FE-89AF-4252-B890-D2C01CB609C1&isPrePop=true&';
						}
						else if ($this->_site['game'] == SLOT)
						{
							$jumpUrl = 'http://www.rewardsflow.com/?Flow=9CE4BAE4-F0C1-43B6-812C-09B056FD0E8B&isPrePop=true&';
						}
						else if ($this->_site['game'] == POKER)
						{
							$jumpUrl = 'http://www.rewardsflow.com/?Flow=64524D96-74FB-447D-9D5A-9B9A130F3867&isPrePop=true&';
						}
						$urlArgs['returnurl'] = $domain . url('user/completed').'?event=full_reg_coreg&coreg=Fluent';
						$record = new Record($uid);
						$record->addCoregRecording('profiling_coreg_start', 'Fluent');
						$_SESSION['redirect_url'] = $jumpUrl . http_build_query($urlArgs);
						$_SESSION['iframe_breaker'] = true;
						return $this->_redirect(url('offer/coreg'));
					}
				}else{
					//if (strtoupper($gender) == 'M')
					if ($seed == 'Fluent')
//					if (false)
					{
						$urlArgs = array('email'=>$email, 'gender'=>$gender, 'dobmonth'=>$birthMonth, 'dobday'=>$birthDay, 'dobyear'=>$birthYear
								,'firstname'=>$firstname, 'lastname'=>$lastname, 'address1'=>$address1, 'address2'=>$address2,'city'=>$city
								,'state'=>$state,'zip'=>$zipcode,'phonecode'=>$countryCode,'phoneprefix'=>$areaCode,'phonesuffix'=>$subscriberNumber, 'won'=>$todaywon, 'header'=>$this->_site['jackpot']
						);
						if($this->_site['game'] == WHEEL)
						{
							$jumpUrl = 'http://www.rewardsflow.com/?Flow=F78B19DD-529A-4452-B595-334BEA911346&isPrePop=true&';
							$urlArgs['returnurl'] = $domain.url('user/completed').'?event=profiling_coreg_end&coreg=Fluent';
						}
						else if ($this->_site['game'] == SLOT)
						{
							$jumpUrl = 'http://www.rewardsflow.com/?Flow=8314C0AD-F6C1-4372-883A-D4F807E6ADB7&isPrePop=true&';
							$urlArgs['returnurl'] = $domain.url('user/completed').'?event=profiling_coreg_end&coreg=Fluent';
						}
						else if ($this->_site['game'] == POKER)
						{
							$jumpUrl = 'http://www.rewardsflow.com/?Flow=913EB1B0-7141-4F2C-95A7-09C5E8882219&isPrePop=true&';
							$urlArgs['returnurl'] = $domain.url('user/completed').'?event=profiling_coreg_end&coreg=Fluent';
						}
						$_SESSION['redirect_url'] = $jumpUrl . http_build_query($urlArgs);
						$record = new Record($uid);
						$record->addCoregRecording('profiling_coreg_start', 'Fluent');
						return $this->_redirect(url('offer/coreg'));
					}else if ($seed == 'Prospectiv'){
						$urlArgs = array('em'=>$email, 'fn'=>$firstname, 'ln'=>$lastname, 'a1'=>$address1, 'a2'=>$address2, 'ci'=>$city, 'st'=>$state, 'zi'=>$zipcode, 'g'=>strtoupper($gender), 'dob'=>$birthMonth.$birthDay.$birthYear, 'ph'=>$countryCode.$areaCode.$subscriberNumber, 'header'=>$this->_site['jackpot']);
						if($this->_site['game'] == WHEEL)
						{
							$jumpUrl = 'http://www.eversave.com/service/servlet/consumers.Redirect?rid=17568&';
							$urlArgs['r'] = $domain.url('user/completed').'?event=profiling_coreg_end&coreg=Prospectiv';
						}
						else if ($this->_site['game'] == SLOT)
						{
							$jumpUrl = 'http://www.eversave.com/service/servlet/consumers.Redirect?rid=17574&';
							$urlArgs['r'] = $domain.url('user/completed').'?event=profiling_coreg_end&coreg=Prospectiv';
						}
						else if ($this->_site['game'] == POKER)
						{
							$jumpUrl = 'http://www.eversave.com/service/servlet/consumers.Redirect?rid=17571&';
							$urlArgs['r'] = $domain.url('user/completed').'?event=profiling_coreg_end&coreg=Prospectiv';
						}
						$record = new Record($uid);
						$record->addCoregRecording('profiling_coreg_start', 'Prospectiv');
						$_SESSION['redirect_url'] = $jumpUrl . http_build_query($urlArgs);
						$_SESSION['iframe_breaker'] = true;
						return $this->_redirect(url('offer/coreg'));
					}else if($seed == "Coolsavings"){
						if ($this->_site['game'] == WHEEL)
						{
							$header = 'http://image.cgb.s3.amazonaws.com/cashdazzle.com/img/header-cashdazzle.png';
							$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=325202&c=&a=111483&t=17501&country=us&';
						}
						else if ($this->_site['game'] == SLOT)
						{
							$header = 'http://image.cgb.s3.amazonaws.com/lalaloot.com/img/header-lalaloot.png';
							$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=325208&c=&a=111483&t=17501&country=us&';
						}
						else if ($this->_site['game'] == POKER)
						{
							$header = 'http://image.cgb.s3.amazonaws.com/mommymoolah.com/img/herder-mommymoolah.png';
							$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=325211&c=&a=111483&t=17501&country=us&';
						}
						$urlArgs = array('a1'=>$address1,
										 'st'=>$state,
										 'zi'=>$zipcode,
										 'ci'=>$city,
										 'em'=>$email, 
										 'fn'=>$firstname, 
										 'ln'=>$lastname,
										 'phone'=>$phone,
										 'bd_y'=>$birthYear,
										 'bd_m'=>$birthMonth, 
										 'bd_d'=>$birthDay, 
										 //'hi'=>$header
										 'ti'=>(strtolower($gender)=='m'?3:2)
										 );
						$urlArgs['redirect_url'] = $domain.url('user/completed').'?event=profiling_coreg_end&coreg=CoolSavings';
						$record = new Record($uid);
						$record->addCoregRecording('profiling_coreg_start', 'Coolsavings');
						$_SESSION['redirect_url'] = $jumpUrl . http_build_query($urlArgs);
						$_SESSION['iframe_breaker'] = true;
						return $this->_redirect(url('offer/coreg'));				
					}
				}
			}else{
				$_SESSION['errors'] = $errors;
				$_SESSION['accountinfo']['email'] = $email;
				$_SESSION['accountinfo']['firstname'] = $firstname;
				$_SESSION['accountinfo']['lastname'] = $lastname;
				$_SESSION['accountinfo']['address1'] = $address1;
				$_SESSION['accountinfo']['address2'] = $address2;
				$_SESSION['accountinfo']['gender'] = $gender;
				$_SESSION['accountinfo']['city'] = $city;
				$_SESSION['accountinfo']['zipcode'] = $zipcode;
				if(strtolower($this->_site['locale']) == 'uk'){
					$_SESSION['accountinfo']['phone'] = $phone;
				}else{
					$_SESSION['accountinfo']['countryCode'] = $countryCode;
					$_SESSION['accountinfo']['areaCode'] = $areaCode;
					$_SESSION['accountinfo']['subscriberNumber'] = $subscriberNumber;
				}
				$_SESSION['accountinfo']['birthDay'] = $birthDay;
				$_SESSION['accountinfo']['birthMonth'] = $birthMonth;
				$_SESSION['accountinfo']['birthYear'] = $birthYear;
				return $this->_redirect(url('user/profile'));
			}
		}
	}
	
	function actionCompleted(){
		if (!empty($_SESSION['iframe_breaker']))
		{
			unset($_SESSION['iframe_breaker']);
			return $this->display($this->_site['template'], 'common/iframebreaker');
		}
		$event = $this->_context->event;
		if (empty($event))
		{
			$event = 'profiling_coreg_end';
		}
		$coreg = $this->_context->coreg;
		$user = $this->_app->currentUser();
		$uid = $user['id'];
		$record = new Record($uid);
		$record->addCoregRecording($event, $coreg);
		if(isset($_SESSION['infos'])){
			$this->_view['infos'] = $_SESSION['infos'];
			unset($_SESSION['info']);
		}
		$usermodel = new User();
		$userInfo = $usermodel->getProfileInfo($user['id']);
		$birthday = $userInfo['birthday'];
		$birth = explode('-', $birthday);
		if(count($birth) == 3){
			unset($userInfo['birthday']);
			$userInfo['birthDay'] = $birth[2];
			$userInfo['birthYear'] = $birth[0];
			$userInfo['birthMonth'] = $birth[1];
		}
		$phoneNums = explode('-', $userInfo['phone']);
		if(count($phoneNums) == 3){
			unset($userInfo['phone']);
			$userInfo['countryCode'] = $phoneNums[0];
			$userInfo['areaCode'] = $phoneNums[1];
			$userInfo['subscriberNumber'] = $phoneNums[2];
		}			
		$this->_view['accountinfo'] = $userInfo;	
		if(isset($_SESSION['accountinfo'])){
			unset($_SESSION['accountinfo']);
		}
		return $this->display($this->_site['template'], 'user/profile');
	}
	
	function actionSignup(){
		if (isset($_SESSION['errors'])){
			$errors = $_SESSION['errors'];
			$this->_view['errors'] = $errors;
			unset($_SESSION['errors']);
		}
		
		if (isset($_SESSION['accountinfo'])) {
			$this->_view['accountinfo'] = $_SESSION['accountinfo'];
	        $birthday = explode('-', $this->_view['accountinfo']['birthday']);
			$this->_view['accountinfo']['birthYear'] = $birthday[0];
			$this->_view['accountinfo']['birthMonth'] = $birthday[1];
			$this->_view['accountinfo']['birthDay'] = $birthday[2];
			unset($_SESSION['accountinfo']);
		}
		return $this->display($this->_site['template']);
	}
	
	function actionFulfillment(){
		if(isset($_SESSION['errors'])){
			$this->_view['errors'] = $_SESSION['errors'];
			unset($_SESSION['errors']);
		}
		return $this->display($this->_site['template']);
	}
	
	function actionFulfilling(){
		if($this->_context->isPOST()){
			$amount = $this->_context->amount;
			$usermodel = new User();
			if(20 <= $amount){
				$result = $usermodel->drawMoney($amount, $this->_view['user']['id']);
				if($result){
					$this->_view['user']['balance'] -= $amount;
					$_SESSION['drawAmount'] = $amount;		
					Util::addNewEmail('fulfillment', $this->_site['template'], 
							array('email'=>$this->_view['user']['email'], 'username' => $this->_view['user']['firstname'], 'amount' => $amount, 'domain'=>$this->_view['site']['domain'], 'uid'=>$this->_view['user']['id']));					
					
					return $this->_redirect(url('user/fulfilled'));
				}else{
					$errors = array();
					$errors[] = Util::getMessage(3001);
					$_SESSION['errors'] = $errors;
					return $this->_redirect(url('user/fulfillment'));	
				}
			}else{
				$errors = array();
				$errors[] = Util::getMessage(3002);
				$_SESSION['errors'] = $errors;
				return $this->_redirect(url('user/fulfillment'));	
			}
		}
	}
	
	function actionFulfilled(){
		if(isset($_SESSION['drawAmount'])){
			$this->_view['amount'] = $_SESSION['drawAmount'];
			unset($_SESSION['drawAmount']);
		}else{
			return $this->_redirect(url('user/account'));
		}
		return $this->display($this->_site['template']);
	}
	
	function actionActive(){
		$token = $this->_context->token;
		$name = $this->_context->name;
		$usermodel = new User();
		$user = $usermodel->confirm($token, $name);
		$domain = $this->getDomainByGameAndLocale($this->_site['game'], $this->_view['site']['locale']);
		if(!empty($user)){
			$this->_app->changeCurrentUser($user, 'MEMBER');
			$usermodel->confirmAccount($user['id']);
			
			//add credit to reference
			if($user['cam'] == 'ref'){
				if ($this->_site['game'] == WHEEL){
					$referenceCredit = 1;
				}else if ($this->_site['game'] == SLOT){
					$referenceCredit = 5;
				}else if ($this->_site['game'] == POKER){
					$referenceCredit = 1;
				}
				$usermodel->rewardReference($user['pla'], $referenceCredit, 'Referred '.$user['email']);
			}else if($user['cam'] == '17' || $user['cam'] == '18'){
				if($user['fired'] != '1'){
					$s2scamModel = new S2scam();
					$s2scamModel->add($user['cam'], str_replace('CD', '', $user['pub']), $user['pla']);
					$usermodel->setFired($user['id']);
				}
			}
			
			$settingModel = new Settings();
			$settingData = $settingModel->getConf();
			foreach($settingData as $v){
				$conf[$v['k']]=$v['v'];
			}
			$seeds = array();
			for($i = 0; $i < $conf['emactive_fluent_value']; $i++){
				$seeds[]='Fluent';
			}
			for($i = 0; $i < $conf['emactive_prospectiv_value']; $i++){
				$seeds[]='Prospectiv';
			}
			for($i = 0; $i < $conf['emactive_coolsavings_value']; $i++){
				$seeds[]='Coolsavings';
			}
			$ind = rand(0, (count($seeds)-1));
			$seed = $seeds[$ind];
			if(strtolower($this->_site['locale']) == 'uk'){
				if (false)
				{
					list($byear, $bmonth, $bday) = explode('-', $user['birthday']);
					$todaywon = $usermodel->getTodayWon($this->_site['id']);
					$urlArgs = array('email'=>$user['email'], 'gender'=>$user['gender'], 'dobmonth'=>$bmonth, 'dobday'=>$bday, 'dobyear'=>$byear
								,'firstname'=>$user['firstname'], 'lastname'=>$user['lastname'], 'won'=>$todaywon, 'header'=>$this->_site['jackpot']
					);
					if($this->_site['game'] == WHEEL)
					{
						$jumpUrl = 'http://www.rewardsflow.com/?Flow=B353C2FE-89AF-4252-B890-D2C01CB609C1&isPrePop=true&';
					}
					else if ($this->_site['game'] == SLOT)
					{
						$jumpUrl = 'http://www.rewardsflow.com/?Flow=9CE4BAE4-F0C1-43B6-812C-09B056FD0E8B&isPrePop=true&';
					}
					else if ($this->_site['game'] == POKER)
					{
						$jumpUrl = 'http://www.rewardsflow.com/?Flow=64524D96-74FB-447D-9D5A-9B9A130F3867&isPrePop=true&';
					}
					$urlArgs['returnurl'] = $domain . url('user/actived').'?event=confirmed_coreg&coreg=Fluent';
					$record = new Record($user['id']);
					$record->addCoregRecording('confirmed_coreg', 'Fluent');
				}
				else
				{
					list($byear, $bmonth, $bday) = explode('-', $user['birthday']);
					if ($this->_site['game'] == WHEEL)
					{
						$header = 'http://image.cgb.s3.amazonaws.com/cashdazzle.co.uk/img/header-cashdazzle.png';
						$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=323314&t=17501&c=&a=111483&country=uk&';
					}
					else if ($this->_site['game'] == SLOT)
					{
						$header = 'http://image.cgb.s3.amazonaws.com/lalaloot.co.uk/img/header-lalaloot.png';
						$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=323315&t=17501&c=&a=111483&country=uk&';
					}
					else if ($this->_site['game'] == POKER)
					{
						$header = 'http://image.cgb.s3.amazonaws.com/mommymoolah.co.uk/img/herder-mommymoolah.png';
						$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=323316&t=17501&c=&a=111483&country=uk&';
					}
					$urlArgs = array('em'=>$user['email'], 'fn'=>$user['firstname'], 'ln'=>$user['lastname'], 'bd_y'=>$byear, 'bd_m'=>$bmonth, 'bd_d'=>$bday, 'ti'=>(strtolower($user['gender'])=='m'?3:2), 'hi'=>$header);
					$urlArgs['redirect_url'] = $domain.url('user/actived').'?coreg=CoolSavings';
					$record = new Record($user['id']);
					$record->addCoregRecording('confirmed_coreg', 'CoolSavings');
				}
			}
			else
			{
				if ($seed == "Fluent")
//				if (true)
				{
					list($byear, $bmonth, $bday) = explode('-', $user['birthday']);
					$todaywon = $usermodel->getTodayWon($this->_site['id']);
					$urlArgs = array('email'=>$user['email'], 'gender'=>$user['gender'], 'dobmonth'=>$bmonth, 'dobday'=>$bday, 'dobyear'=>$byear
								,'firstname'=>$user['firstname'], 'lastname'=>$user['lastname'], 'won'=>$todaywon, 'header'=>$this->_site['jackpot']
					);
					if($this->_site['game'] == WHEEL)
					{
						$jumpUrl = 'http://www.rewardsflow.com/?Flow=2C8F654B-E51D-4CB5-9614-82A7E80F8109&isPrePop=true&';
					}
					else if ($this->_site['game'] == SLOT)
					{
						$jumpUrl = 'http://www.rewardsflow.com/?Flow=DEE09F2B-6E96-4F13-BCE2-7AF80111675E&isPrePop=true&';
					}
					else if ($this->_site['game'] == POKER)
					{
						$jumpUrl = 'http://www.rewardsflow.com/?Flow=467A6423-26D9-4527-B295-E82423F85C08&isPrePop=true&';
					}
					$urlArgs['returnurl'] = $domain . url('user/actived').'?event=confirmed_coreg&coreg=Fluent';
					$record = new Record($user['id']);
					$record->addCoregRecording('confirmed_coreg', 'Fluent');
				}
				else if($seed == "Prospectiv")
				{
					$urlArgs = array('em'=>$user['email'], 'fn'=>$user['firstname'], 'ln'=>$user['lastname'], 'g'=>strtoupper($user['gender']), 'dob'=>$user['birthday'], 'header'=>$this->_site['jackpot']);
					if($this->_site['game'] == WHEEL)
					{
						$jumpUrl = 'http://www.eversave.com/service/servlet/consumers.Redirect?rid=17569&';
						$urlArgs['r'] = $domain.url('user/actived').'?coreg=Prospectiv';
					}
					else if ($this->_site['game'] == SLOT)
					{
						$jumpUrl = 'http://www.eversave.com/service/servlet/consumers.Redirect?rid=17575&';
						$urlArgs['r'] = $domain.url('user/actived').'?coreg=Prospectiv';
					}
					else if ($this->_site['game'] == POKER)
					{
						$jumpUrl = 'http://www.eversave.com/service/servlet/consumers.Redirect?rid=17572&';
						$urlArgs['r'] = $domain.url('user/actived').'?coreg=Prospectiv';
					}
					$record = new Record($user['id']);
					$record->addCoregRecording('confirmed_coreg', 'Prospectiv');
				}
				else if($seed == "Coolsavings"){
					list($byear, $bmonth, $bday) = explode('-', $user['birthday']);
					if ($this->_site['game'] == WHEEL)
					{
						$header = 'http://image.cgb.s3.amazonaws.com/cashdazzle.com/img/header-cashdazzle.png';
						$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=323481&t=17501&c=&a=111483&country=us&';
					}
					else if ($this->_site['game'] == SLOT)
					{
						$header = 'http://image.cgb.s3.amazonaws.com/lalaloot.com/img/header-lalaloot.png';
						$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=323482&t=17501&c=&a=111483&country=us&';
					}
					else if ($this->_site['game'] == POKER)
					{
						$header = 'http://image.cgb.s3.amazonaws.com/mommymoolah.com/img/herder-mommymoolah.png';
						$jumpUrl = 'http://lgn6.coolsavings.com/rd_p?p=323483&t=17501&c=&a=111483&country=us&';
					}
					$urlArgs = array('a1'=>$user['address1'],
									 'st'=>$user['state'],
									 'em'=>$user['email'], 
									 'fn'=>$user['firstname'], 
									 'ln'=>$user['lastname'],
									 'phone'=>$user['phone'],
									 'bd_y'=>$byear, 
									 'bd_m'=>$bmonth, 
									 'bd_d'=>$bday, 
									 'ti'=>(strtolower($user['gender'])=='m'?3:2), 
									 'hi'=>$header);
					$urlArgs['redirect_url'] = $domain.url('user/actived').'?coreg=CoolSavings';
					$record = new Record($user['id']);
					$record->addCoregRecording('confirmed_coreg', 'CoolSavings');					
				}
			}
			
			$_SESSION['redirect_url'] = $jumpUrl . http_build_query($urlArgs);
			$_SESSION['iframe_breaker'] = true;
			$_SESSION['confirmed'] = true;
			return $this->_redirect(url('offer/coreg'));
		}else{
			return $this->_redirect(url('user/invalid'));
		}
	}
	
	function actionActived(){
		if ($_SESSION['confirmed']) {
			if ($user = $this->_app->currentUser())
			{
//				$record = new Record($user['id']);
//				$record->addCoregRecording('confirm_coreg_end', $this->_context->coreg);
				
				$usermodel = new User();
				if ($this->_site['game'] == WHEEL)
				{
					$usermodel->offerUserCredits(1, $user['id']);
					$credit = 1;
				}
				else if ($this->_site['game'] == SLOT)
				{
					$usermodel->offerUserCredits(5, $user['id']);
					$credit = 5;
				}
				else if ($this->_site['game'] == POKER)
				{
					$usermodel->offerUserCredits(1, $user['id']);
					$credit = 1;
				}
	
				$usermodel->clearToken($user['id']);
				$record = new Record($user['id']);
				$record->addConfirmRecording($credit, $this->_context->coreg);
			}
			unset($_SESSION['confirmed']);
			$this->_view['user']['credit'] += $credit;
			return $this->display($this->_site['template']);
		}else{
			return $this->_redirect(url('default/index'));
		}
	}
	
	function actionInvalid(){
		return $this->display($this->_site['template']);
	}
	
	function actionAdflow(){
		if($event = $this->_context->event)	
		{
			$user = $this->_app->currentUser();
			$uid = $user['id'];
			$record = new Record($uid);
			$record->addCoregRecording($event);
		}
		$this->_view['redirect_url'] = $_SESSION['redirect_url'];
		unset($_SESSION['redirect_url']);
		return $this->display($this->_site['template']);
	}
	
	function actionAdheader(){
		$model = new User();
		$this->_view['today'] = $model->getTodayWon($this->_site['id']);
		return $this->display($this->_site['template']);
	}
	
	function actionStep1(){
		return $this->display($this->_site['template']);
	}
	
	function actionStep2(){
		if($currentUser = $this->_app->currentUser()){
			$this->_view['uid'] = $currentUser['id'];
			require_once APPLICATION_PATH . '/library/facebook/facebook.php';
			
			$facebook = new Facebook($this->_view['fbsocials']);
			$facebook->setAccessToken(isset($_SESSION['fb_js_token'])? $_SESSION['fb_js_token'] : null);
			$user = $facebook->getUser();
			if($user){
				try{
					$user_profile = $facebook->api('/me');
					$this->_view['fbuid'] = $user_profile['id'];
					$this->_view['fb_js_token'] = $_SESSION['fb_js_token'];
				}catch (FacebookApiException $e){
					error_log($e);
	  			}
			}
			
			return $this->display($this->_site['template']);		
		}else{
			return $this->_redirect(url('user/login'));
		}
	}
	
	function actionStep3(){
		if($currentUser = $this->_app->currentUser()){			
			$this->_view['uid'] = $currentUser['id'];
			return $this->display($this->_site['template']);		
		}else{
			return $this->_redirect(url('user/login'));
		}
	}
	
	function actionStep4(){
		if($currentUser = $this->_app->currentUser()){			
			$this->_view['uid'] = $currentUser['id'];
			return $this->display($this->_site['template']);		
		}else{
			return $this->_redirect(url('user/login'));
		}
	}

	
	function actionGetfriends(){
		$_SESSION['fb_js_token'] = $this->_context->post('js_token', null);
		$this->_view['js_token'] = $this->_context->post('js_token', null);
		$_SESSION['fb_user_words'] = $this->_context->post('fb_user_words', null);
		return $this->display($this->_site['template']);
	}
	
	function actionPublishonwall(){
		require_once APPLICATION_PATH . '/library/facebook/facebook.php';
		
		$facebook = new Facebook($this->_view['fbsocials']);
		$facebook->setAccessToken($this->_context->post('js_token', null));
		
		$user = $facebook->getUser();
		if($user){
			try{
				$user_profile = $facebook->api('/me');		
			}catch (FacebookApiException $e){
				error_log($e);
  			}
  			$message = isset($_SESSION['fb_user_words'])? $_SESSION['fb_user_words'] : '';
  			$message .= "hey, check out this new game I am playing , they are giving away real Cash !  here’s the site to sign up. http://www.{$this->_view['site']['domain']}?cam=ref&pub=fb&pla={$this->_view['user']['id']}";
			$friendArray = explode( ',' , $this->_context->post('friends', '') );
			$friendArray[] = $user_profile['id'];
			
			foreach( $friendArray as $friend ){
				try{
					$facebook->api('/'.$friend.'/feed/', 'post', array('link' => "", 'message' => $message));
				} catch (FacebookApiException $e) {
					if($e->getMessage() == '(#506) Duplicate status message') {
						
					}else{
						throw new Model_Exception($e->getMessage(), $e->getCode());
					}
				}
			}
			if ($user = $this->_app->currentUser())
			{
				$record = new Record($user['id']);
				$record->addShareRecording('ref_facebook', 'share_facebook', count($friendArray));
			}
			
			return 'true';
		}else{
			return 'Please login!';
		}

	}
	
	function actionGetcontacts(){
			require_once APPLICATION_PATH . '/library/Svetlozar.NET/init.php';

			$return = array ();
			$contacts_classes = ContactsHelper::$ContactsClasses;
			//! determine where to import contacts from based on contacts option value (Yahoo, Gmail etc)
			$selected_option = $this->_context->get('contacts_option', null);
			//! back to the beginning, importing contacts: check if selected option maps to an actual class (we don't trust our users)
			$current_class = isset ( $contacts_classes [$selected_option] ) ? $contacts_classes [$selected_option] : null;
			if (! $current_class) {
				$return ['error'] = true;
				$return ['errorMessage'] = "Invalid option {$selected_option}";
			} else {
				//! get any state information pertinent to the request and remove it from session immediately
				//! (it will not be valid on next request, and may or may not be updated after attempt to import contacts)
				$state = isset($_SESSION[$selected_option])? $_SESSION[$selected_option] : null;
				unset($_SESSION[$selected_option]);
				//! session is not the only place where we can store state information, add any more state info from the form if available
				if ($this->_context->get('state', null)){
					//$state = $state ? "{$state}&{$params["state"]}" : $params ["state"];
					$state = $this->_context->get('state', null);
				}
				//! include only the file of the specific contacts importer class
				ContactsHelper::IncludeClassFile ( $current_class->FileName ); //!< This actually checks if the file is valid contacts importer class before loading the file
				//! determine if ExtAuth needs to be added to the name of the class for external authentication, and then create a new instance of contacts importer class that corresponds to the selected option
				if ($current_class->ExternalAuth) {
					$class_name = $current_class->ClassName . "ExtAuth";
					$contacts_importer = new $class_name ();
				}else if($this->_context->get('email', null)){ //!< if this is not external authentication form, extract any fields from the form that we need for creating a class instance
					//list ( $email, $password, $captcha ) = SPUtils::get_values ( $this->_context, "email", "pswd", "captcha" );
					$email = $this->_context->get('email', null);
					$password = $this->_context->get('password', null);
					$contacts_importer = new $current_class->ClassName ( $email, $password, null );
				}
				//! make sure instance of the contacts importer class has been created
				if (!$contacts_importer) {
					$return ['error'] = true;
					$return ['errorMessage'] = "Could not initialize contacts importer.";
				}else{
					//! restore previously stored state (see above - this was combination of state stored in session + state submitted with the form)
					if ($state) {
						$contacts_importer->RestoreState ( $state );
					}
					//! $contacts_importer->contacts automagically loads the contacts data on success, returns null otherwise
					//! it will also accept Contacts (it's a getter property)
					if ($contacts = $contacts_importer->contacts) {
						//! you could store the list of contacts at this point, the example code displays it for selection
						$return = $contacts;
					}else{ //!< if null or no contacts returned examine any error conditions
						$return ['error'] = true;
						switch ($contacts_importer->Error) {
							case ContactsResponses::ERROR_INVALID_LOGIN :
								$return ['errorMessage'] = "<div style='color:red;width:200px;padding:0px 0px;'>The email or password you entered is incorrect.</div>";
								break;
							case ContactsResponses::ERROR_EXTERNAL_AUTH :
								$return ['errorMessage'] = "External Authentication Required";
								break;
							case ContactsResponses::ERROR_NO_CONTACTS :
								$return ['errorMessage'] = "No contacts were found";
								break;
							case ContactsResponses::ERROR_NO_USERPASSWORD :
								$return ['errorMessage'] = "Provide Email and Password";
								break;
							case ContactsResponses::ERROR_CAPTCHA_REQUIRED :
								//! a note on captcha, if we get it as a response we need to display it ($this is available in the form when it is included)
								$return ['errorMessage'] = "Enter captcha to continue";
								$return ['captcha'] = 'true';
								$return ['captcha_url'] = $contacts_importer->CaptchaUrl;
								break;
							default :
								//! generic error
								$return ['errorMessage'] = "Request could not be handled. Try again Later.";
								break;
						}
					}
					//! get any state information from the contacts importer class
					$state = $contacts_importer->GetState ();
					//! if state is not empty and there has not been an error or the error requires state (captcha and external authentication both need to maintain state between requests)
					if ($state && (!$contacts_importer->Error || $contacts_importer->Error == ContactsResponses::ERROR_CAPTCHA_REQUIRED || $contacts_importer->Error == ContactsResponses::ERROR_EXTERNAL_AUTH)) {
						// store the state info to session
						//$this->add_to_session ( $selected_option, $state );
						$_SESSION[$selected_option] = $state;
					}
				}
			}
			return json_encode ( $return );
			//$this->session_commit ();
	}
	
	function actionTellfriends(){
 		if($currentUser = $this->_app->currentUser()){
 			$userModel = new User();
 			$userInfo = $userModel->getProfileInfo($currentUser['id']);
			$emailsSendto = $this->_context->post('selected_users', null);
			$emailType = $this->_context->post('mail_server', null);
			$emailsSendto = array_slice($emailsSendto, 0, 10);
			foreach($emailsSendto as $email){
				Util::addNewEmail('share', $this->_site['template'], array('email'=>$email, 'reference'=>$userInfo['id'], 'username'=>$userInfo['firstname'].' '.$userInfo['lastname']
										,'domain'=>$this->_site['domain'], 'name' => $this->_site['name'],'emailType' => $emailType, 'url' => "http://www.{$this->_site['domain']}".url('default/share'), 'priority'=>30));
			}
			$record = new Record($currentUser['id']);
			$record->addShareRecording('ref_email', 'share_email',  count($emailsSendto));
			return 'success';//return $this->_redirect(url('user/step2'));
		}else{
			return 'islogout';//return $this->_redirect(url('user/login'));
		}
	}
	
	function actionFollowers(){
		$screenName = $_POST['screenName'];
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
		curl_setopt($ch, CURLOPT_URL, "https://api.twitter.com/1/followers/ids.json?cursor=-1&screen_name=" . $screenName);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST,'GET');
		$followersCount = 0;
		if ($result = curl_exec($ch)) {
			$followersObj = json_decode($result);
			$followersCount = count($followersObj->ids);
		}
		curl_close($ch);
		if ($user = $this->_app->currentUser())
		{
			$record = new Record($user['id']);
			$record->addShareRecording('ref_twitter', 'share_twitter',  $followersCount);
		}		
	}
	
	function actionReferfriends(){
		if($currentUser = $this->_app->currentUser()){
			$this->_view['uid'] = $currentUser['id'];
			require_once APPLICATION_PATH . '/library/facebook/facebook.php';
			
			$facebook = new Facebook($this->_view['fbsocials']);
			$facebook->setAccessToken(isset($_SESSION['fb_js_token'])? $_SESSION['fb_js_token'] : null);
			$user = $facebook->getUser();
			if($user){
				try{
					$user_profile = $facebook->api('/me');
					$this->_view['fbuid'] = $user_profile['id'];
					$this->_view['fb_js_token'] = $_SESSION['fb_js_token'];
				}catch (FacebookApiException $e){
					error_log($e);
	  			}
			}
			
			return $this->display($this->_site['template']);		
		}else{
			return $this->_redirect(url('user/login'));
		}
	}
	
	private function getDomainByGameAndLocale($game, $locale)
	{
		$locale = strtolower($locale);
		if($game == WHEEL){
			if($locale == 'uk'){
				$domain = 'http://www.cashdazzle.co.uk';
			}else{
				$domain = 'http://www.cashdazzle.com';
			}
		}else if ($game == SLOT){
			if($locale == 'uk'){
				$domain = 'http://www.lalaloot.co.uk';
			}else{
				$domain = 'http://www.lalaloot.com';
			}
		}else if ($game == POKER){
			if($locale == 'uk'){
				$domain = 'http://www.mommymoolah.co.uk';
			}else{
				$domain = 'http://www.mommymoolah.com';
			}
		}
		
		return $domain;
	}
}
?>